﻿using System;
using System.Collections;
using System.Configuration.Install;
using System.IO;
using System.Security.Principal;
using System.ServiceProcess;

namespace X18.Framework.Core.Service
{
    /// <summary>
    /// Windows 服务安装及启动工具
    /// </summary>
    public class WindowsServiceHelper
    {
        /// <summary>
        /// 程序正在以管理员身份运行
        /// </summary>
        public static bool IsRunningAsAdministrator()
        {
            // 获取当前用户的身份
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            // 检查是否属于管理员组
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }

        /// <summary>
        /// 安装服务
        /// </summary>
        /// <param name="serviceFilePath">服务文件所在路径</param>
        public static void Install(string serviceFilePath)
        {
            AssemblyInstaller installer = new AssemblyInstaller(serviceFilePath, null);
            IDictionary state = new Hashtable();
            installer.UseNewContext = true;
            installer.Install(state);
            installer.Commit(state);
            installer.Dispose();
        }

        /// <summary>
        /// 卸载服务
        /// </summary>
        /// <param name="serviceFilePath">服务文件所在路径</param>
        public static void Uninstall(string serviceFilePath)
        {
            AssemblyInstaller installer = new AssemblyInstaller(serviceFilePath, null);
            IDictionary state = new Hashtable();
            installer.UseNewContext = true;
            installer.Uninstall(state);
            installer.Dispose();
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        public static void Start(string serviceName)
        {
            ServiceController service = new ServiceController(serviceName);
            if (service.Status != ServiceControllerStatus.Running)
            {
                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(0));
            }
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        public static void Stop(string serviceName)
        {
            ServiceController service = new ServiceController(serviceName);
            if (service.Status != ServiceControllerStatus.Stopped)
            {
                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMilliseconds(0));
            }
        }
    }
}
